package com.insmess.speech.service.impl;

import com.insmess.speech.common.util.InsmessFileUtils;
import com.insmess.speech.sdk.dto.VectorResponseDto;
import com.insmess.speech.sdk.template.FfmpegTemplate;
import com.insmess.speech.sdk.template.InsmessVectorTemplate;
import com.insmess.speech.service.VoiceprintService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
public class VoiceprintServiceImpl implements VoiceprintService {
    @Autowired
    private InsmessVectorTemplate insmessVectorTemplate;

    @Autowired
    private FfmpegTemplate ffmpegTemplate;

    @Override
    public Double comapreByArray(Double[] vecOne, Double[] vecTwo) {
        VectorResponseDto vectorResponseDto = insmessVectorTemplate.vectorCompare(vecOne, vecTwo);
        if (!vectorResponseDto.getCode().equals(200)) {
            throw new RuntimeException("声纹对比失败");
        }
        VectorResponseDto.Result result = vectorResponseDto.getResult();
        return result.getScore();
    }

    @SneakyThrows
    @Override
    public Double comapreByFile(MultipartFile fileOne, MultipartFile fileTwo) {
        File tmpAudioFileOne = InsmessFileUtils.getTmpFile(fileOne);
        File tmpAudioFileTwo = InsmessFileUtils.getTmpFile(fileTwo);
        return comapreByFile(tmpAudioFileOne, tmpAudioFileTwo);
    }

    @Override
    public Double comapreByFile(File fileOne, File fileTwo) {
        InsmessFileUtils.checkFormat(fileOne);
        InsmessFileUtils.checkFormat(fileTwo);
        //将语音文件转成wav
        File audioFileOne = ffmpegTemplate.formatWav(fileOne);
        //将语音文件转成wav
        File audioFileTwo = ffmpegTemplate.formatWav(fileTwo);
        VectorResponseDto vectorResponseDto = insmessVectorTemplate.vectorScoreRequest(audioFileOne.getAbsolutePath(), audioFileTwo.getAbsolutePath());
        if (!vectorResponseDto.getCode().equals(200)) {
            throw new RuntimeException("声纹对比失败");
        }
        VectorResponseDto.Result result = vectorResponseDto.getResult();
        return result.getScore();
    }

    @Override
    public Double[] getVoiceprint(File file) {
        InsmessFileUtils.checkFormat(file);
        //将语音文件转成wav
        File audioFile = ffmpegTemplate.formatWav(file);
        return insmessVectorTemplate.vectorRequest(audioFile.getAbsolutePath());
    }

    @SneakyThrows
    @Override
    public Double[] getVoiceprint(MultipartFile file) {
        File tmpAudioFile = InsmessFileUtils.getTmpFile(file);
        return getVoiceprint(tmpAudioFile);
    }
}
